﻿using System;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using nyxwin.Data.Session;
using nyxwin.Common.Settings;
using System.Linq;

namespace nyxwin.Main.View
{
    public partial class LoginPage : PhoneApplicationPage
    {
        ApplicationBarIconButton buttonLogin = null;

        #region Construction
        public LoginPage()
        {
            InitializeComponent();
        }
        #endregion

        #region PhoneApplicationPageLoaded
        private void PhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {
            textBoxUserName.Text = !string.IsNullOrEmpty(ApplicationSettings.Instance.AuthorizationNick) ? ApplicationSettings.Instance.AuthorizationNick : string.Empty;
            textBoxToken.Text = !string.IsNullOrEmpty(ApplicationSettings.Instance.AuthorizationCode) ? ApplicationSettings.Instance.AuthorizationCode : string.Empty;

            foreach (var button in ApplicationBar.Buttons)
            {
                if (button is ApplicationBarIconButton && (button as ApplicationBarIconButton).Text == "Login")
                {
                    buttonLogin = button as ApplicationBarIconButton;
                    break;
                }
            }

            buttonLogin.IsEnabled = false;

            NavigationService.RemoveBackEntries();
        }
        #endregion

        #region ButtonRequestAuthorization_OnClick
        private void ButtonRequestAuthorization_OnClick(object sender, RoutedEventArgs e)
        {
            var me = this;
            var progressIndicator = new ProgressIndicator { IsVisible = true, IsIndeterminate = true, Text = "Requesting authorization token..." };

            var loginMgr = new LoginManager();
            loginMgr.LoginCompleted += (evSender, evArgs)
              => Dispatcher.BeginInvoke(delegate
                                        {
                                            progressIndicator.IsVisible = false;
                                            SystemTray.SetIsVisible(me, false);

                                            if (evArgs.Error)
                                                MessageBox.Show(evArgs.ErrorMessage, "Error occurred", MessageBoxButton.OK);
                                            else
                                            {
                                                if (evArgs.AuthorizationStatus == "AUTH_EXISTING")
                                                {
                                                    MessageBox.Show("You have already authorized this application.", "Error", MessageBoxButton.OK);

                                                    textBoxStatus.Text = evArgs.AuthorizationStatus;
                                                    textBoxComment.Text = "Please de-authorize this application on nyx.cz/personal/settings/authorization first!";
                                                }
                                                else if (evArgs.AuthorizationStatus == "AUTH_NEW")
                                                {
                                                    ApplicationSettings.Instance.AuthorizationNick = evArgs.AuthorizationNick;
                                                    ApplicationSettings.Instance.AuthorizationToken = evArgs.AuthorizationToken;

                                                    ApplicationSettings.Instance.AuthorizationCode = evArgs.AuthorizationCode;
                                                    textBoxToken.Text = evArgs.AuthorizationCode;

                                                    textBoxStatus.Text = evArgs.AuthorizationStatus;
                                                    textBoxComment.Text = "";

                                                    buttonLogin.IsEnabled = true;
                                                }
                                                else
                                                {
                                                    MessageBox.Show(string.Format("Unknown authorization status = '{0}', please report it to developers !", 
                                                        evArgs.AuthorizationStatus), "Error", MessageBoxButton.OK);
                                                }
                                            }
                                        });

            SystemTray.SetIsVisible(me, true);
            SystemTray.SetOpacity(me, 0.5);
            SystemTray.SetProgressIndicator(me, progressIndicator);

            loginMgr.Authorize(textBoxUserName.Text, textBoxToken.Text);
        }
        #endregion

        #region buttonLogin_Click
        private void ButtonLogin_OnClick(object sender, EventArgs e)
        {
            var authNick = ApplicationSettings.Instance.AuthorizationNick = textBoxUserName.Text;
            var authToken = ApplicationSettings.Instance.AuthorizationCode = textBoxToken.Text;

            if (string.IsNullOrEmpty(authNick) ||
                string.IsNullOrEmpty(authToken))
            {
                MessageBox.Show("Please enter correct information to continue.", "Warning", MessageBoxButton.OK);
                return;
            }

            NavigationService.Navigate(new Uri("/StartupPage.xaml", UriKind.Relative));
        }
        #endregion

        #region OnNavigatedTo
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            NavigationService.RemoveBackEntries();
        }
        #endregion
    }
}